package kvm

import (
	"github.com/go-resty/resty/v2"
	"strings"
)

type Node struct {
	Hostname string
	IP       string
	Status   string
}

type NodeStatusRaw struct {
	InstanceName string   `json:"instance_name"`
	IP           []string `json:"ip"`
	Cmd          string   `json:"cmd"`
	Res          string   `json:"res"`
}

// GetStatus 获取node的状态
func (n *Node) GetStatus() string {
	url := kvmDomain + pathOfStatus
	params := map[string]string{
		"vm_name": n.Hostname,
		"ip":      n.IP,
	}
	res := new(NodeStatusRaw)
	_, err := resty.New().R().SetQueryParams(params).SetResult(&res).Post(url)
	if err != nil {
		return "fail: " + err.Error()
	}
	sp := strings.Split(res.Res, n.Hostname)
	if len(sp) < 2 {
		return ""
	}
	n.Status = strings.TrimSpace(sp[1])
	return n.Status
}

func (n *Node) AddToWhiteList() error {
	url := kvmDomain + pathOfAdd
	params := map[string]string{
		"ip": n.IP,
	}
	_, err := resty.New().R().SetQueryParams(params).Post(url)
	if err != nil {
		return err
	}
	return nil
}

func (n *Node) Start() error {
	url := kvmDomain + pathOfStart
	params := map[string]string{
		"vm_name": n.Hostname,
		"ip":      n.IP,
	}
	_, err := resty.New().R().SetQueryParams(params).Post(url)
	if err != nil {
		return err
	}
	return nil
}

func (n *Node) Stop(force bool) error {
	url := kvmDomain + pathOfShutdown
	if force {
		url = kvmDomain + pathOfDestroy
	}
	params := map[string]string{
		"vm_name": n.Hostname,
		"ip":      n.IP,
	}
	_, err := resty.New().R().SetQueryParams(params).Post(url)
	if err != nil {
		return err
	}
	return nil
}
